package com.fushenlan.epidemicControl.sms;

import cn.hutool.core.util.HexUtil;
import cn.hutool.http.HttpUtil;
import com.fushenlan.epidemicControl.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送短信等的组件
 *
 * @author Administrator
 * @date 2022/4/22 21:24
 */
@Component
@Slf4j
public class SmsUtil {

    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private EncryptUtil encryptUtil;

    /**
     * 发送短信
     *
     * @param phoneNo 电话
     * @param msg     消息内容
     * @return 响应结果
     */
    public Map<String, String> sendMessage(String phoneNo, String msg) {
        String url = smsConfig.getUrl();
        //GBK编码短信内容
        String gbkMsg = HexUtil.encodeHexStr(smsConfig.getMessageTemplate().replace("{VeriCode}", msg), Charset.forName("GBK"));
        url = url.replace("{SPID}", encryptUtil.decrypt(smsConfig.getSpid()))
                .replace("{PWD}", encryptUtil.decrypt(smsConfig.getSppassword()))
                .replace("{PHONE}", "86" + phoneNo)
                .replace("{MESSAGE}", gbkMsg);
        String resp = HttpUtil.get(url);
        log.info("send msg({}) to:{}", msg, url);
        log.info("resp:{}", resp);
        //解析响应 command=MT_RESPONSE&spid=****&mtmsgid=118464012710100208&mtstat=ACCEPTD&mterrcode=000
        String[] split = resp.split("&");
        Map<String, String> map = new HashMap<>();
        for (String s : split) {
            String[] strings = s.split("=");
            map.put(strings[0], strings[1]);
        }
        return map;
    }
}
